package service

import (
	"lktx-dns/bean"
	"lktx-dns/config"
	"lktx-dns/db"
	"lktx-dns/entity"
)

type DomainService struct {
}

func (receiver DomainService) InitConfigProxy() {
	var results []*entity.DomainInfoEntity
	db.DB.Model(&entity.DomainInfoEntity{}).Where("status = 1 ").Find(&results)
	config.Records.Range(func(key, value any) bool {
		config.Records.Delete(key)
		return true
	})
	for _, result := range results {
		value, ok := config.Records.Load(*result.Domain)
		if ok {
			entities := value.([]*entity.DomainInfoEntity)
			entities = append(entities, result)
			config.Records.Store(*result.Domain, entities)
		} else {
			var infos []*entity.DomainInfoEntity
			infos = append(infos, result)
			config.Records.Store(*result.Domain, infos)
		}
	}
}

func (receiver *DomainService) DomainList(page int, pageSize int) *bean.ResPage {
	receiver.InitConfigProxy()
	var results []*entity.DomainInfoEntity
	var total int64
	db.DB.Model(&entity.DomainInfoEntity{}).Order("id desc").Count(&total).Offset((page - 1) * pageSize).Limit(pageSize).Find(&results)
	// 计算总记录数并执行分页查询
	return bean.PageOk(total, results)
}

func (receiver *DomainService) DomainListByKey(keyword string) *bean.ResData {
	var results []entity.DomainInfoEntity
	tx := db.DB.Model(&entity.DomainInfoEntity{})
	if len(keyword) > 0 {
		tx.Where("domain like ?", "%"+keyword+"%")
	}
	tx.Order("id desc").Find(&results)
	return bean.ResOk(results)
}

func (receiver *DomainService) RemoveData(id int) bool {
	userQuery := &entity.DomainInfoEntity{}
	db.DB.Where("id = ? ", id).First(userQuery)
	if userQuery != nil {
		var results entity.DomainInfoEntity
		db.DB.Where("id = ?", id).Delete(&results)
		receiver.InitConfigProxy()
		return true
	}
	return false
}

func (receiver *DomainService) SaveData(userDomain entity.DomainInfoEntity) error {
	if userDomain.Id == nil {
		db.DB.Save(&userDomain)
	} else {
		db.DB.Model(&entity.DomainInfoEntity{}).Where("id = ?", userDomain.Id).Update("type", userDomain.Type).Update("status", userDomain.Status).Update("record", userDomain.Record).Update("domain", userDomain.Domain).Update("desc", userDomain.Desc)
	}
	receiver.InitConfigProxy()
	return nil
}

func (receiver *DomainService) UpdateStatus(id int, status string) error {
	db.DB.Model(&entity.DomainInfoEntity{}).Where("id = ?", id).Update("status", status)
	receiver.InitConfigProxy()
	return nil
}
